# 统一返回
import json

from zz import zz_str


def of(errcode, errmsg=""):
    r = Return(errcode, errmsg)
    return r


# 字符串转 return
def parse(json_str):
    r = of(0)
    dd = {}
    try:
        dd = json.loads(json_str)
    except Exception as ex:
        errmsg = f"json解析异常：{ex}"
        r.set_errcode(123456)
        r.set_errmsg(errmsg)
        print(errmsg)

    if isinstance(dd, dict):
        for k, v in dd.items():
            r.set_data(k, v)

    return r


class Return:
    def __init__(self, errcode, errmsg=""):
        self.data = {
            "errcode": errcode,
            "errmsg": errmsg,
        }

    def set_data(self, k, v):
        # if isinstance(v, str):
        #     v = v.decode('utf-8')
        self.data[k] = v

    def get_data(self, k, def_val=None):
        if k not in self.data:
            return def_val
        return self.data[k]

    def get_errcode(self):
        return self.data["errcode"]

    def set_errcode(self, errcode):
        if isinstance(errcode, str):
            errcode = zz_str.to_int(errcode)
        if not isinstance(errcode, int):
            return

        self.data["errcode"] = errcode

    def get_errmsg(self):
        return self.data["errmsg"]

    def set_errmsg(self, errmsg):
        self.data["errmsg"] = errmsg

    def ok(self):
        return self.get_errcode() == 0

    def err(self):
        return not self.ok()

    def to_json(self):
        return json.dumps(self.data, ensure_ascii=False)
        # return json.dumps(self.data, ensure_ascii=False)
